package com.tanhua.server.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.common.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 用来调用OSS进行token校验
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    private RestTemplate restTemplate;

    //获得配置文件中的OSS服务的地址
    @Value("${tanhua.sso.url}")
    private String ossUrl;

    //反序列化
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    /**
     * 请求OSS，校验token，返回User对象
     * @param token
     * @return
     */
    public User queryUserByToken(String token) {
        //拼接url将token以get方式请求到OSS对应的方法上
        String url = ossUrl+"/user/"+token;

        try {
            //返回OSS结果的json
            String data = restTemplate.getForObject(url, String.class);
            //返回的是个null就返回null
            if (StringUtils.isEmpty(data)){
                return null;
            }
            //反序列化成User对象，返回
            return OBJECT_MAPPER.readValue(data,User.class);
        } catch (IOException e) {
            log.error("通过OSS校验token时出错，token="+token,e);
        }
        return null;
    }
}
